package com.hc.componentspringboot.util;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.UUID;

/**
 * JWT(了解)
 */
public class JwtUtil {
    static long time = 1000 * 15;
    static String sign = "admin";
    public static String generateToken(){
        JwtBuilder builder = Jwts.builder();
        String jwt = builder
                .setHeaderParam("type","JWT")//头部分
                .setHeaderParam("alg","HS256")
                .claim("username","tom")//中间部分
                .claim("role","admin")
                .setSubject("admin-test")
                .setExpiration(new Date(System.currentTimeMillis() + time))
                .setId(UUID.randomUUID().toString())
                .signWith(SignatureAlgorithm.HS256,sign)//签名部分
                .compact();
        return jwt;
    }

    public static boolean checkTokenValid(String token){
        if(token == null || "".equals(token)){
            return false;
        }
        try {
            JwtParser parser = Jwts.parser();
            parser.setSigningKey(sign).parseClaimsJws(token);
        }catch (Exception e){
            return false;
        }
        return true;
    }
}
